package com.jiuyou.clientController.coupons;

import com.alibaba.fastjson.JSONObject;
import com.jiuyou.clientController.base.ClientBaseController;
import com.ruoyi.common.constant.DicConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.DateUtils;
import com.ruoyi.coupons.domain.Coupons;
import com.ruoyi.coupons.domain.CouponsMember;
import com.ruoyi.coupons.service.ICouponsMemberService;
import com.ruoyi.coupons.service.ICouponsService;
import com.ruoyi.product.domain.StoreProduct;
import com.ruoyi.product.domain.StoreProductBack;
import com.ruoyi.product.service.IStoreProductBackService;
import com.ruoyi.product.service.IStoreProductService;
import com.ruoyi.shopping.domain.CouponsVo;
import com.ruoyi.store.domain.Store;
import com.ruoyi.store.service.IStoreService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 优惠券
 *
 * @author jiuyou
 */
@Api(tags = {"C端红包相关"})
@RestController
@RequestMapping("/client/coupons")
public class CouponsClientController extends ClientBaseController {
    private static final Logger log = LoggerFactory.getLogger(CouponsClientController.class);
    @Autowired
    private ICouponsService couponsService;
    @Autowired
    private ICouponsMemberService couponsMemberService;
    @Autowired
    private IStoreProductService storeProductService;
    @Autowired
    private IStoreProductBackService bakService;
    @Autowired
    private IStoreService storeService;
    /**
     * 查询我的优惠券列表
     */
    @ApiOperation(value = "查询我的优惠券列表，可用优惠券列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "pageNum", value = "当前第几页", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "pageSize", value = "每页几条数据", required = true, dataType = "Integer"),
            @ApiImplicitParam(name = "storeId", value = "可使用门店id", dataType = "Long"),
            @ApiImplicitParam(name = "useState", value = "是否已使用，已使用Y未使用传N", dataType = "String"),
            @ApiImplicitParam(name = "canUseState", value = "是否可用", dataType = "String"),
            @ApiImplicitParam(name = "overdueStateParam", value = "是否已过期，已过期Y未过期传N", dataType = "String"),
    })
    @PostMapping("/listMyCoupons")
    public AjaxResult listMyCoupons(String useState, String canUseState, String overdueStateParam, Long storeId, Integer pageNum, Integer pageSize) {
        Long memberId = getLoginMemberId();

        if (null == memberId) {
            return AjaxResult.error("登录状态无效");
        }
        CouponsVo vo = new CouponsVo();
        vo.setMemberId(memberId);
        vo.setStoreId(storeId);
        vo.setUseState(useState);
        vo.setCanUseState(canUseState);
        vo.getParams().put("overdueStateParam", overdueStateParam);//是否过期未使用
        startPage();
        List<CouponsVo> list = couponsMemberService.selectMineList(vo);
        List<Long> collect = list.stream().map(CouponsVo::getStoreId).distinct().collect(Collectors.toList());

        HashMap<Long, String> map = new HashMap<>();
        if(collect.size()>0){
            List<Store> stores = storeService.selectStoreListByIds(collect);
            stores.forEach(e->{
                map.put(e.getId(),e.getStoreName());
            });
        }
        TableDataInfo tableDataInfo = getDataTable(list);
        List<JSONObject> jsoList = new ArrayList<>();
        for (CouponsVo couponsVo : list) {
            JSONObject jso = new JSONObject();
            jso.put("couponId", couponsVo.getCouponId());
            jso.put("couponName", couponsVo.getCouponName());
            jso.put("money", couponsVo.getMoney());
            jso.put("minPrice", couponsVo.getMinPrice());
            jso.put("belongType", couponsVo.getBelongType());
            jso.put("primaryKey", couponsVo.getPrimaryKey());
            jso.put("newUserState", couponsVo.getNewUserState());
            jso.put("couponType", couponsVo.getCouponType());
            jso.put("useState", couponsVo.getUseState());
            jso.put("storeId",couponsVo.getStoreId());
            String overdueStateStr = couponsOverdueState(couponsVo.getUseState(), couponsVo.getUseEndTime());
            if (null != overdueStateParam) {
                //如果传了是否过期，则只展示对应的
                if (!overdueStateStr.equals(overdueStateParam)) {

                    continue;
                }
            }
            if(DicConstants.BELONG_TYPE_Store.getCode().equals(couponsVo.getBelongType())){
                if(map.containsKey(couponsVo.getStoreId())){
                    jso.put("storeName",map.get(couponsVo.getStoreId()));
                }
            }
            if(couponsVo.getModelType().equals("MCM")){
                jso.put("storeName","商城券");
            }
            jso.put("overdueState", overdueStateStr);
            jso.put("useTime", DateUtils.dateTimeHMS(couponsVo.getUseTime()));
            jso.put("useStartTime", DateUtils.dateTime(couponsVo.getUseStartTime()));
            jso.put("useEndTime", DateUtils.dateTime(couponsVo.getUseEndTime()));
            jso.put("modelType",couponsVo.getModelType());
            jsoList.add(jso);
        }
        tableDataInfo.setRows(jsoList);
        return AjaxResult.success(tableDataInfo);
    }

    @ApiOperation(value = "查询该商品可用的优惠券,返回未使用，未过期。类型是品类券的包含品类id，商品券的包含商品id，通用券 ，同时满足可用金额")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品id", dataType = "Long"),
    })
    @PostMapping("/listCanUseCoupons")
    public AjaxResult list(Long productId) {
        Long memberId = getLoginMemberId();

        if (null == memberId) {
            return AjaxResult.error("登录状态无效");
        }
        if (null == productId) {
            return AjaxResult.error("参数错误");
        }
        StoreProduct storeProduct = storeProductService.selectStoreProductById(productId);
        if (null == storeProduct) {
            return AjaxResult.error("参数错误");
        }
        String useState = DicConstants.SYS_N.getCode();//未使用
        String overdueStateParam = DicConstants.SYS_N.getCode();//未过期
        String canUseState = DicConstants.SYS_Y.getCode();//可使用
        Long classifyId = storeProduct.getClassifyId();//分类id
        BigDecimal price = storeProduct.getPrice();//可用金额
        CouponsMember couponsMemberParam = new CouponsMember();
        couponsMemberParam.setMemberId(memberId);
        couponsMemberParam.setStoreId(storeProduct.getStoreId());
        couponsMemberParam.setUseState(useState);
        couponsMemberParam.setMinPrice(price);//minPrice<=price 小于等于商品价格才可用
        couponsMemberParam.setCanUseState(canUseState);
        couponsMemberParam.getParams().put("canUseCoupons", "Y");//是否查可使用标记，Y为查
        couponsMemberParam.getParams().put("classifyId", classifyId);//商品分类id
        couponsMemberParam.getParams().put("productId", productId);//商品id

        return AjaxResult.success(getTableDataInfo(couponsMemberParam, overdueStateParam));
    }

    private TableDataInfo getTableDataInfo(CouponsMember couponsMemberParam, String overdueStateParam) {
        couponsMemberParam.getParams().put("overdueStateParam", overdueStateParam);//是否过期未使用
        startPage();
        List<CouponsMember> list = couponsMemberService.selectCouponsMemberList(couponsMemberParam);
        List<Long> collect = list.stream().map(CouponsMember::getStoreId).distinct().collect(Collectors.toList());
        List<Store> stores = storeService.selectStoreListByIds(collect);
        HashMap<Long, String> map = new HashMap<>(stores.size());
        stores.forEach(e->{
            map.put(e.getId(),e.getStoreName());
        });
        TableDataInfo tableDataInfo = getDataTable(list);
        List<JSONObject> jsoList = new ArrayList<>();
        for (CouponsMember couponsMember : list) {
            JSONObject jso = new JSONObject();
            jso.put("couponId", couponsMember.getCouponId());
            jso.put("couponName", couponsMember.getCouponName());
            jso.put("money", couponsMember.getMoney());
            jso.put("minPrice", couponsMember.getMinPrice());
            jso.put("belongType", couponsMember.getBelongType());
            jso.put("primaryKey", couponsMember.getPrimaryKey());
            jso.put("newUserState", couponsMember.getNewUserState());
            jso.put("couponType", couponsMember.getCouponType());
            jso.put("useState", couponsMember.getUseState());
            jso.put("storeId",couponsMember.getStoreId());
            String overdueStateStr = couponsOverdueState(couponsMember.getUseState(), couponsMember.getUseEndTime());
            if (null != overdueStateParam) {
                //如果传了是否过期，则只展示对应的
                if (!overdueStateStr.equals(overdueStateParam)) {

                    continue;
                }
            }
            if(DicConstants.BELONG_TYPE_Store.getCode().equals(couponsMember.getBelongType())){
                if(map.containsKey(couponsMember.getStoreId())){
                    jso.put("storeName",map.get(couponsMember.getStoreId()));
                }
            }
            jso.put("overdueState", overdueStateStr);
            jso.put("useTime", DateUtils.dateTimeHMS(couponsMember.getUseTime()));
            jso.put("useStartTime", DateUtils.dateTime(couponsMember.getUseStartTime()));
            jso.put("useEndTime", DateUtils.dateTime(couponsMember.getUseEndTime()));
            jsoList.add(jso);
        }
        tableDataInfo.setRows(jsoList);
        return tableDataInfo;
    }

    /**
     * 返回是否过期，只有未使用的才有过期一说，
     *
     * @param useState
     * @param useEndTime
     * @return
     */
    private String couponsOverdueState(String useState, Date useEndTime) {
        if (DicConstants.SYS_N.getCode().equals(useState)) {
            if (new Date().compareTo(useEndTime) > 0) {
                //当前日期超过可使用日期
                //已过期
                return DicConstants.SYS_Y.getCode();
            }
        }
        //未过期
        return DicConstants.SYS_N.getCode();
    }


    @ApiOperation(value = "查询该商品可领取的优惠券")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "productId", value = "商品id", dataType = "Long"),
    })
    @PostMapping("/listCanGetCoupons")
    public AjaxResult listCanGetCoupons(Long productId) {
        //
        if (null == productId) {
            return AjaxResult.error("参数错误");
        }
        StoreProduct storeProduct = storeProductService.selectStoreProductById(productId);
        if (null == storeProduct) {
            return AjaxResult.error("参数错误");
        }
        Long storeId = storeProduct.getStoreId();//门店id
        boolean isNewUser = isNewUser(storeId);
        Long classifyId = storeProduct.getClassifyId();//分类id
        BigDecimal price = storeProduct.getPrice();//可用金额
        String newUserState = null;
        if (!isNewUser) {
            newUserState = DicConstants.SYS_N.getCode();
        }
        Coupons couponsParam = new Coupons();
        couponsParam.setStoreId(storeId);
        couponsParam.setNewUserState(newUserState);
        couponsParam.setMinPrice(price);
        couponsParam.setState(DicConstants.SYS_Y.getCode());
        couponsParam.getParams().put("canUseCoupons", "Y");//是否查可使用标记，Y为查
        couponsParam.getParams().put("classifyId", classifyId);//商品分类id
        couponsParam.getParams().put("productId", productId);//商品id
        startPage();
        List<Coupons> list = couponsService.selectCouponsList(couponsParam);
        TableDataInfo tableDataInfo = getDataTable(list);
        List<JSONObject> jsoList = new ArrayList<>();
        for (Coupons coupons : list) {
            JSONObject jso = new JSONObject();
            jso.put("couponName", coupons.getCouponName());
            jso.put("money", coupons.getMoney());
            jso.put("minPrice", coupons.getMinPrice());
            jso.put("belongType", coupons.getBelongType());
            jso.put("newUserState", coupons.getNewUserState());
            jso.put("couponType", coupons.getCouponType());
            jso.put("fixedTimeState", coupons.getFixedTimeState());
            jso.put("useStartTime", coupons.getUseStartTime());
            jso.put("useEndTime", coupons.getUseEndTime());
            jso.put("validDay", coupons.getValidDay());
            jsoList.add(jso);
        }
        tableDataInfo.setRows(jsoList);
        return AjaxResult.success();
    }

    @PostMapping("/listCanGet/{storeId}")
    public AjaxResult getStoreCoupons(@PathVariable Long storeId) {
        Coupons coupons = new Coupons();
        coupons.setStoreId(storeId);
        coupons.setState(DicConstants.SYS_Y.getCode());
        coupons.setCreateType(DicConstants.BUSINESS_Business.getCode());
        ArrayList<Coupons> list = new ArrayList<>();
        //商家券
        List<Coupons> storeList = couponsService.selectCouponsList(coupons);
        Coupons platForm = new Coupons();
        platForm.setState(DicConstants.SYS_Y.getCode());
        platForm.setCreateType(DicConstants.BUSINESS_Manager.getCode());

        //
        List<Coupons> platFormList = couponsService.selectCouponsList(platForm);
        list.addAll(storeList);
        list.addAll(platFormList);
        ArrayList<JSONObject> jsonObjects = new ArrayList<>();
        list.forEach(e -> {
            JSONObject j = new JSONObject();
            j.put("price", e.getMoney());
            j.put("minPrice", e.getMinPrice());
            j.put("id", e.getId());
            jsonObjects.add(j);
        });
        return AjaxResult.success(jsonObjects);
    }

    @PostMapping("/receive/{couponId}")
    public AjaxResult receive(@PathVariable Long couponId) {
        Long loginMemberId = getLoginMemberId();
        Coupons coupons = couponsService.selectCouponsById(couponId);
        if(DicConstants.SYS_Y.getCode().equals(coupons.getLimitedState())){
            if(coupons.getLastTotal()<=0L){
                return AjaxResult.error("优惠券已被抢光了");
            }
        }
        CouponsMember params = new CouponsMember();
        params.setCouponId(couponId);
        params.setMemberId(loginMemberId);
        List<CouponsMember> list = couponsMemberService.selectCouponsMemberList(params);
        if (list.size() > 0) {
            return AjaxResult.error("已领取当前优惠券");
        }
        //判断是否是当前门店新人,如果是门店新人随意领取
        if(DicConstants.SYS_Y.getCode().equals(coupons.getNewUserState())){
            if(!isNewUser(coupons.getStoreId())){
                return AjaxResult.error("仅限新人领取");
            }
        }

        CouponsMember couponsMember = new CouponsMember();
        couponsMember.setStoreId(coupons.getStoreId());
        couponsMember.setCouponId(couponId);
        couponsMember.setCanUseState(coupons.getState());
        couponsMember.setCouponName(coupons.getCouponName());
        couponsMember.setMoney(coupons.getMoney());
        couponsMember.setMinPrice(coupons.getMinPrice());
        couponsMember.setReceiveType(DicConstants.RECEIVE_TYPE_Receive.getCode());
        couponsMember.setCouponType(coupons.getCouponType());
        couponsMember.setBelongType(coupons.getBelongType());
        if (DicConstants.SYS_Y.getCode().equals(coupons.getFixedTimeState())) {
            couponsMember.setUseStartTime(new Date());
            couponsMember.setUseEndTime(DateUtils.addDate(coupons.getValidDay().intValue()));
        } else {
            couponsMember.setUseStartTime(coupons.getUseStartTime());
            couponsMember.setUseEndTime(coupons.getUseEndTime());
        }
        couponsMember.setPrimaryKey(coupons.getPrimaryKey());
        couponsMember.setUseState(DicConstants.SYS_N.getCode());
        couponsMember.setMemberId(loginMemberId);
        couponsMember.setNewUserState(coupons.getNewUserState());
        couponsMember.setNewUserState(coupons.getNewUserState());
        if (DicConstants.SYS_Y.getCode().equals(coupons.getLimitedState())) {
            coupons.setLastTotal(coupons.getTotal() - 1L);
            couponsService.updateCoupons(coupons);
        }
        couponsMemberService.insertCouponsMember(couponsMember);
        return AjaxResult.success("领取成功");
    }

    @PostMapping("/listStoreMyCoupons/{storeId}")
    public AjaxResult listStoreMyCoupons(@PathVariable Long storeId) {
        Long memberId = getLoginMemberId();

        if (null == memberId) {
            return AjaxResult.error("登录状态无效");
        }
        CouponsMember couponsMember = new CouponsMember();
        couponsMember.setMemberId(memberId);
        couponsMember.setStoreId(storeId);
        List<CouponsMember> list = couponsMemberService.selectCouponsMemberList(couponsMember);
        CouponsMember platform = new CouponsMember();
        platform.setMemberId(memberId);
        List<CouponsMember> couponsMembers = couponsMemberService.selectCouponsMemberList(platform);
        ArrayList<CouponsMember> result = new ArrayList<>();
        result.addAll(list);
        result.addAll(couponsMembers);
        List<CouponsMember> unique = result.stream().collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(CouponsMember::getId))), ArrayList::new)
        );
        TableDataInfo tableDataInfo = getDataTable(unique);
        return AjaxResult.success(tableDataInfo);
    }

    @PostMapping("/getCanUseCoupons")
    public AjaxResult getCanUseCoupons(String useState, String canUseState, String overdueStateParam, Long storeId,Long bakId,String productId) {
        Long memberId = getLoginMemberId();

        if (null == memberId) {
            return AjaxResult.error("登录状态无效");
        }
        StoreProductBack back = bakService.selectStoreProductBackById(bakId);
        CouponsMember couponsMember = new CouponsMember();
        couponsMember.setMemberId(memberId);
        couponsMember.setStoreId(storeId);
        couponsMember.setUseState(useState);
        couponsMember.setCanUseState(canUseState);
        couponsMember.getParams().put("classifyId",back.getClassifyId());
        couponsMember.getParams().put("productId",productId);
        couponsMember.getParams().put("overdueStateParam", overdueStateParam);
        couponsMember.getParams().put("canUseCoupons", "Y");
        couponsMember.setMinPrice(back.getPrice());
        couponsMember.setBelongType(DicConstants.BELONG_TYPE_Store.getCode());
        List<CouponsMember> list = couponsMemberService.selectCouponsMemberList(couponsMember);
        CouponsMember platParams = new CouponsMember();
        platParams.setMemberId(memberId);
        platParams.setUseState(useState);
        platParams.setCanUseState(canUseState);
        platParams.getParams().put("classifyId",back.getClassifyId());
        platParams.getParams().put("productId",productId);
        platParams.getParams().put("overdueStateParam", overdueStateParam);
        platParams.getParams().put("canUseCoupons", "Y");
        platParams.setBelongType(DicConstants.BELONG_TYPE_Plateform.getCode());
        platParams.setMinPrice(back.getPrice());
        List<CouponsMember> plat = couponsMemberService.selectCouponsMemberList(platParams);
        List<CouponsMember> couponsMembers = new ArrayList<>();
        couponsMembers.addAll(plat);
        couponsMembers.addAll(list);
        TableDataInfo tableDataInfo = getDataTable(couponsMembers);
        return AjaxResult.success(tableDataInfo);
    }


    public static void main(String[] args) {
        System.out.println(c());
    };
    private static int c(){
        try{
            int[] a = new int[1];
            return 1;
        }catch (Exception e){
            return 2;
        }finally {
            return 3;
        }

    }
}
